package com.keyin;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;

import com.keyin.protocol.CacheImageProtocol;
import com.keyin.protocol.MagazineIndexCache;
import com.keyin.protocol.Periodical;
import com.keyin.protocol.Protocol;
import com.keyin.protocol.ProtocolHelper;

public class CatalogActivity extends BaseActivity {

	private Periodical periodical;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		String peridocalId = getIntent().getExtras().getString("peridocal_id");
		periodical = MagazineIndexCache.get(peridocalId);
		if (periodical == null) {
			new AlertDialog.Builder(this)
					.setTitle("提示")
					.setMessage("杂志文件出错，请重新下载")
					.setPositiveButton("取消",
							new DialogInterface.OnClickListener() {

								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									finish();
								}
							}).show();
		}

		setContentView(R.layout.a_catalog);

		GridView grid = (GridView) findViewById(R.id.magazine_catalog);
		grid.setAdapter(new BaseAdapter() {

			@Override
			public View getView(int position, View convertView, ViewGroup parent) {

				Protocol p = ProtocolHelper.getPeriodical(
						getApplicationContext(), periodical.periodical_id,
						position + 1);
				String url = p.getUrl();
				url = CacheImageProtocol.encode(url);

				ImageView img = new ImageView(getApplicationContext());
				img.setLayoutParams(new AbsListView.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
				try {
					img.setImageBitmap(BitmapFactory.decodeFile(App.root + "thumb_"+url));
				} catch (Exception e) {
					e.printStackTrace();
				}
				return img;
			}

			@Override
			public long getItemId(int position) {
				return 0;
			}

			@Override
			public Object getItem(int position) {
				return null;
			}

			@Override
			public int getCount() {
				return periodical.pages;
			}
		});
		grid.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {

				Intent i = new Intent(CatalogActivity.this, ReadMagazineActivity.class);
				i.putExtra("page", position + 1);
				i.putExtra("peridocal_id",periodical.periodical_id);
				startActivity(i);
			}
		});
	}
}
